package com.gensdai.leliang.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.gensdai.leliang.R;
import com.gensdai.leliang.adapter.Delivery_address_adapter;
import com.gensdai.leliang.base.BaseActivityNoAbs;
import com.gensdai.leliang.dialog.Upload;
import com.gensdai.leliang.entity.Address;
import com.gensdai.leliang.json_base.json_base;
import com.gensdai.leliang.remoteInterface.ApiService;
import com.trello.rxlifecycle2.android.ActivityEvent;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/6/2.
 */

public class Delivery_address extends BaseActivityNoAbs implements View.OnClickListener {

    public static final int RESULT_DELETE = 0x999;

    @BindView(R.id.ui_title)
    TextView uiTitle;
    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.address)
    ListView address;
    @BindView(R.id.new_address)
    TextView newAddress;
    @BindView(R.id.no_default_address)
    TextView noDefaultAddress;

    Delivery_address_adapter DAA;
    List<Address> list_data = null;
    private Upload up;
    SharedPreferences share;
    SharedPreferences.Editor ed;

    private final int ENTER = 1;
    private final int DELETE = 2;
    private final int DEFAULT = 3;

    int flag = -1;  //从那个界面过来的意图是什么
    private Handler handler = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case ENTER:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if (list_data != null) {
                                list_data.clear();
                            }
                            list_data = (List<Address>) new json_base().jsonDelivery(new JSONObject((String) msg.obj));
                            SetmList();
                        } else {

                        }
//                        Toast.makeText(
//                                Delivery_address.this,
//                                new JSONObject((String) msg.obj)
//                                        .getString("message"),
//                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case DELETE:
                    up.dismiss();
                    setResult(RESULT_DELETE, null);
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            QueryRequestStr();
                        } else {

                        }
                        Toast.makeText(
                                Delivery_address.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                case DEFAULT:
                    up.dismiss();
                    try {
                        if (new json_base().GOOD((String) msg.obj)) {
                            if(flag == 1){
                                add = addNewAddress;
                                Intent intent = new Intent();
                                intent.putExtra("address", add);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("address", add);
                                intent.putExtras(bundle);
                                setResult(RESULT_OK, intent);
                                Delivery_address.this.finish();
                            }else{
                                QueryRequestStr();
                            }
                        } else {

                        }
                        Toast.makeText(
                                Delivery_address.this,
                                new JSONObject((String) msg.obj)
                                        .getString("message"),
                                Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    up.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.delivery_address);
        ButterKnife.bind(this);

        flag = getIntent().getIntExtra("flag", -1);
        init();
//        SetmList();
    }

    /**
     * 初始化
     */
    private void init() {
        uiTitle.setText(getString(R.string.delivery_address));
        back.setOnClickListener(this);
        newAddress.setOnClickListener(this);
        list_data = new ArrayList<Address>();
        share = getSharedPreferences("User", MODE_PRIVATE);
        ed = share.edit();
        up = new Upload(this);
    }


    private void SetmList() {
        if (list_data == null) {
            noDefaultAddress.setVisibility(View.VISIBLE);
            address.setVisibility(View.GONE);
            return;
        }
        noDefaultAddress.setVisibility(View.GONE);
        address.setVisibility(View.VISIBLE);
        DAA = new Delivery_address_adapter(this, list_data, sd);
        address.setAdapter(DAA);
        DAA.notifyDataSetChanged();

        address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //当flag为1的时候是从生成订单的界面过来 选择地址的
                if (flag == 1) {
                    add = (Address) adapterView.getItemAtPosition(i);
                    Intent intent = new Intent();
                    intent.putExtra("address", add);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("address", add);
                    intent.putExtras(bundle);
                    setResult(RESULT_OK, intent);
                    Delivery_address.this.finish();
                }

            }
        });
    }

    Address add;
    /**
     * 回调删除某一个地址
     */
    Delivery_address_adapter.setdata sd = new Delivery_address_adapter.setdata() {
        @Override
        public void deleteListData(int position) {
            RemoveAddressRequestStr(position);
        }

        @Override
        public void defaultListData(int position) {
            SetDefaultAddressRequestStr(position);
            ed.putString("name", list_data.get(position).getUser_name());
            ed.putString("province", list_data.get(position).getCityId());
            ed.putString("addressId", list_data.get(position).getId());
            ed.putString("detailAddress", list_data.get(position).getAddress());
            ed.putString("adressPhone", list_data.get(position).getPhone());
            ed.commit();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                this.finish();
                break;
            case R.id.new_address:
                Intent go_new_address = new Intent(this, New_delivery_address.class);
                startActivity(go_new_address);
                break;
            default:
                break;
        }
    }

    /**
     * 调用查询收货地址
     */
    private void QueryRequestStr() {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));   //用户id
        loginParams.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
//        loginParams.put("userId","");   //用户id
//        loginParams.put("transferMoney", "7");   //用户id
//        loginParams.put("payee_real_name", "沙箱环境");   //用户id


        toStr(loginParams);
    }

    //返回字符串类型
    private void toStr(Map<String, String> loginParams) {
        up.show();
//        ApiService.getInstance(this).tixian(loginParams)
        ApiService.getInstance(this).QueryRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = ENTER;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    /**
     * 调用删除收货地址--------------------------------------------------
     */
    private void RemoveAddressRequestStr(int position) {
        //获取edit的值后请求

        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));   //用户id
        loginParams.put("addressId", list_data.get(position).getId());   //收货地址IDS
        loginParams.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        deletetoStr(loginParams);
    }

    //返回字符串类型
    private void deletetoStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).RemoveAddressRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = DELETE;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }


    Address addNewAddress;

    /**
     * 调用设置默认收货地址--------------------------------------------------
     */
    private void SetDefaultAddressRequestStr(int position) {
        //获取edit的值后请求
        addNewAddress = list_data.get(position);
        Map<String, String> loginParams = new HashMap<>();
        loginParams.put("userId", share.getString("user_id", ""));   //用户id
        loginParams.put("addressId", list_data.get(position).getId());   //收货地址IDS
        loginParams.put("token", getSharedPreferences("User", MODE_PRIVATE).getString("token", ""));
        SetDefaultAddressRequestStr(loginParams);
    }

    //返回字符串类型
    private void SetDefaultAddressRequestStr(Map<String, String> loginParams) {
        up.show();
        ApiService.getInstance(this).SetDefaultAddressRequestStr(loginParams)
                //涉及到IO操作
                .subscribeOn(Schedulers.io())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
////                        if (hud != null) {
////                            hud.show();
////                        }

                        Log.d("accept", "accept");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        //可以取消订阅
                        //还可以判断是否处于取消状态
                        //boolean b=d.isDisposed();

                        Log.d("onSubscribe", "onSubscribe");
                    }

                    @Override
                    public void onNext(@NonNull String s) {
                        //处理得到的数据
                        Log.e("quick_login", s);
                        Message msg = new Message();
                        msg.what = DEFAULT;
                        msg.obj = s;
                        handler.sendMessage(msg);
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        //异常处理
                        up.dismiss();
                        Log.e("onError", e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        //监听完毕后的处理
                        Log.d("onComplete", "onComplete");
                    }
                });
    }

    @Override
    protected void onStart() {
        super.onStart();
        QueryRequestStr();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
